<!-- 年规 - 供应链规划 - 主页 -->
<template>
  <z-paging-list ref="list" :hide-empty-view="isSocietyManager" :loading-more-enabled="false" @loadData="loadData">
    <template #top>
      <view class="flex justify-between items-center px-3.75 py-3 text-28 c-#999">
        <view>币种：{{ currencyName }}</view>
        <view v-if="isSocietyManager" @click="onChargeUserClick">
          <text>负责人：</text>
          <text class="c-primary">{{ state.chargeUser?.nickname || '待添加' }}</text>
        </view>
        <view v-else>负责人：{{ state.chargeUser?.nickname || '--' }}</view>
      </view>
      <view class="flex justify-center">
        <u-tabs v-model="state.tabIndex" :list="tabList" bg-color="none" :is-scorll="false" bar-height="6" bar-width="36"
          active-color="#333" inactive-color="#999" font-size="32" :bar-style="{ backgroundColor: '#F4AF22' }"
          @change="refresh" />
      </view>
    </template>
    <template #default v-if="!state.loading">
      <template v-if="state.tabIndex == 0">
        <view v-if="state.productList.length > 0">
          <view v-for="(item, index) in state.productList" :key="index" class="product-item">
            <view class="flex items-center">
              <image class="w-45 h-45 rounded-5 overflow-hidden"
                :src="`/package_plan/static/images/ic_product${item.type}.png`" />
              <view class="ml-3.75 text-32 c-#333">{{ productTypeName(item.type) }}</view>
            </view>
            <view class="mt-2 px-3.75 py-2 bg-#f6f6f6 rounded-2">
              <view v-for="(product, productIndex) in item.product_info" :key="productIndex"
                class="flex mb-1 text-24 c-#333">
                <view class="flex-shrink-0">产品{{ productIndex + 1 }}</view>
                <view class="flex-1 ml-3.5">{{ product.content }}</view>
              </view>
            </view>
          </view>
        </view>
        <view v-else-if="isSocietyManager || isPlanManager" class="card flex flex-col justify-center items-center"
          @click="navigate(`product/add`)">
          <u-icon name="plus" color="#F4AF22" size="120" />
          <view class="mt-5 text-28 c-primary">添加产品规划</view>
        </view>
        <view v-else class="h-800 flex flex-col justify-center items-center">
          <z-empty imgWidth="200" imgHeight="200" descText="暂无产品规划" />
        </view>
      </template>
      <template v-if="state.tabIndex == 1">
        <view v-if="state.supplierList.length > 0">
          <view v-for="(item, index) in state.supplierList" :key="index" class="product-item"
            @click="navigate(`supplier/add?id=${item.id}`)">
            <view class="flex items-center pr-10">
              <view class="text-32 c-#333 text-maxline-1">{{ item.company_name || '' }}</view>
              <u-icon name="arrow-right" size="24" color="#666" />
            </view>
            <view class="mt-2 grid grid-cols-2 gap-3 text-24">
              <view class="flex items-center mb-1">
                <view class="flex-shrink-0 w-146 c-#999">公司地址</view>
                <view class="flex-1 c-#333 text-maxline-1">{{ item.company_address || '' }}</view>
              </view>
              <view class="flex items-center mb-1">
                <view class="flex-shrink-0 w-146 c-#999">联系人</view>
                <view class="flex-1 c-#333 text-maxline-1">{{ item.contact || '' }}</view>
              </view>
              <view class="flex items-center mb-1">
                <view class="flex-shrink-0 w-146 c-#999">电话</view>
                <view class="flex-1 c-#333 text-maxline-1">{{ item.mobile || '' }}</view>
              </view>
              <view class="flex items-center mb-1">
                <view class="flex-shrink-0 w-146 c-#999">主营产品</view>
                <view class="flex-1 c-#333 text-maxline-1">{{ item.main_product || '' }}</view>
              </view>
              <view class="flex items-center mb-1">
                <view class="flex-shrink-0 w-146 c-#999">供应规模</view>
                <view class="flex-1 c-#333 text-maxline-1">{{ item.supply_scale || '' }}</view>
              </view>
              <view class="flex items-center mb-1">
                <view class="flex-shrink-0 w-146 c-#999">总成交金额</view>
                <view class="flex-1 c-#333 text-maxline-1">{{ numFormat(item.gross_transaction || 0) }}</view>
              </view>
              <view class="flex items-center mb-1">
                <view class="flex-shrink-0 w-146 c-#999">供应商等级</view>
                <view class="flex-1 c-#333 text-maxline-1">{{ item.supplier_level || '' }}</view>
              </view>
              <view class="flex items-center mb-1">
                <view class="flex-shrink-0 w-146 c-#999">供应模式</view>
                <view class="flex-1 c-#333 text-maxline-1">{{ item.supplier_model || '' }}</view>
              </view>
            </view>
            <image v-if="isSocietyManager || isPlanManager" class="absolute top-0 right-0 w-70 h-50"
              src="/package_plan/static/images/ic_delete.png" @click.stop="onSupplierDelete(item)" />
          </view>
        </view>
        <view v-else-if="isSocietyManager || isPlanManager" class="card flex flex-col justify-center items-center"
          @click="navigate(`supplier/add`)">
          <u-icon name="plus" color="#F4AF22" size="120" />
          <view class="mt-5 text-28 c-primary">添加供应商</view>
        </view>
        <view v-else class="h-800 flex flex-col justify-center items-center">
          <z-empty imgWidth="200" imgHeight="200" descText="暂无供应商" />
        </view>
      </template>
    </template>
    <template #bottom>
      <template v-if="isSocietyManager || isPlanManager">
        <template v-if="state.tabIndex == 0">
          <view class="px-3.75 pt-1.5 bg-white" @click="navigate(`product/add`)">
            <view class="btn-primary_plain">编辑</view>
          </view>
        </template>
        <template v-if="state.tabIndex == 1">
          <view class="px-3.75 pt-1.5 bg-white" @click="navigate(`supplier/add`)">
            <view class="btn-primary">添加供应商</view>
          </view>
        </template>
      </template>
    </template>
  </z-paging-list>
</template>
<script setup>
import { navigate, showModal, showToast } from '@/common/util/uni';
import { numFormat } from '@/common/util/format';
import { productTypeList } from '@/common/constant/plan';
import { getChargeDetail, getProductDetail, getSupplierList, deleteSupplier, postChargeAdd } from '@/common/http/module/plan';

import { usePlanStore } from '@/store/plan'
import { useUserStore } from '@/store/user'

const userStore = useUserStore()
const planStore = usePlanStore()

const list = ref();
const state = reactive({
  loading: true,
  chargeUser: '',
  productList: '',
  supplierList: '',
  tabIndex: 0
});

const tabList = [{ name: '产品规划' }, { name: '供应商库' }];

const currencyName = computed(() => planStore.currency?.label || '未添加');
const isSocietyManager = computed(() => userStore.isSocietyManager || userStore.isSocietyCreator)
const isPlanManager = computed(() => userStore.userInfo.id == state.chargeUser?.id)
const productTypeName = computed(() => (type) => productTypeList.find((item) => item.value == type)?.label || '');

async function loadData() {
  state.loading = true;
  if (state.tabIndex == 0) {
    await loadProductData();
  } else {
    await loadSupplierData();
  }
  state.loading = false;
}

async function loadProductData() {
  try {
    const productRes = await getProductDetail(userStore.currentSocietyId, planStore.year);
    state.productList = productRes.data?.filter(item => item.product_info && item.product_info.length > 0);
  } catch (error) {
    console.log('getProductDetail error', error);
  }

  try {
    const chargeRes = await getChargeDetail(userStore.currentSocietyId, planStore.year);
    state.chargeUser = chargeRes.data?.supply_planning;
  } catch (error) {
    console.log('getChargeDetail error', error);
  }
}

async function loadSupplierData() {
  const { data } = await getSupplierList(userStore.currentSocietyId, planStore.year);
  state.supplierList = data;
}

function onSupplierDelete(item) {
  showModal({
    content: '确定要删除这个供应商吗？',
    confirmText: '取消',
    cancelText: '确定',
    success: ({ confirm }) => {
      if (confirm) return;
      deleteSupplier(item.id).then(() => {
        showToast('删除成功');
        refresh();
      });
    },
  });
}


function onChargeUserClick() {
  const ids = state.chargeUser?.user_id
  navigate(`/package_plan/pages/user/select?ids=${ids}&singleSelect=true`)
}

function onMemberChange(list) {
  if (!list || list.length == 0) return
  const user = list[0]
  state.chargeUser = {
    user_id: user.user_id,
    nickname: user.user?.nickname
  }

  const params = {
    club_id: userStore.currentSocietyId,
    year: planStore.year,
    supply_planning_charge: user.user_id
  }
  postChargeAdd(params)
}

function refresh() {
  list.value.onRefresh();
}

defineExpose({ refresh, onMemberChange });
</script>

<style>
page {
  height: 100%;
  background-color: #f8f8f8;
}
</style>

<style lang="scss" scoped>
.card {
  margin: 30rpx;
  padding: 40rpx;
  border-radius: 12rpx;
  background-color: #ffffff;
  box-shadow: -2rpx 4rpx 12rpx 2rpx rgba(206, 143, 12, 0.1);
  overflow: hidden;
}

.product-item {
  position: relative;
  margin: 20rpx 30rpx 0 30rpx;
  padding: 30rpx;
  border-radius: 12rpx;
  background-color: #ffffff;
  box-shadow: -2rpx 4rpx 12rpx 0 rgba(206, 143, 12, 0.1);
}
</style>
